﻿Imports System.Net
Imports System.Net.Mail
Public Class frm_email
    Dim test As Integer = 0
    Private Sub btnsendmail_Click(sender As System.Object, e As System.EventArgs) Handles btnsendmail.Click
        ProgressBar1.Text = "Đang gửi>>>"
            TestTextbox()
        If test = 1 Then
            Dim FilePath As String = txtattach.Text
            Dim UserName As String = txtuser.Text
            Dim Password As String = txtpassword.Text
            Dim UserName1 As String = txtuser1.Text
            Dim mail As MailMessage = New MailMessage
            Dim subject As String = txtsubject.Text
            Dim body As String = rtbbody.Text

            Try
                mail.From = New MailAddress(UserName)
                mail.To.Add(New MailAddress(UserName1))
                mail.Subject = subject
                mail.Body = body
                If FilePath <> "" Then
                    Dim attach As New Attachment(FilePath)
                    mail.Attachments.Add(attach)
                End If
                mail.IsBodyHtml = True
                Dim client As SmtpClient = New SmtpClient("smtp.gmail.com", 587)
                client.EnableSsl = True
                client.Credentials = New System.Net.NetworkCredential(UserName, Password)
                client.Send(mail)
                ProgressBar1.Value = 100
                ProgressBar1.Text = "Gửi thành công!"
                MsgBox("Đã gửi email thành công đến " + UserName1, MsgBoxStyle.Information, "Thông báo")
            Catch ex As Exception
                ProgressBar1.Text = "Thất bại!"
                ProgressBar1.Enabled = False
                MessageBox.Show("Gửi email thất bại, vui lòng thử lại")
                ProgressBar1.Value = 0
            End Try
        End If

    End Sub

    Private Function TestTextbox()
        If (Trim(txtuser.Text) = "" Or Trim(txtpassword.Text) = "" Or Trim(txtuser1.Text) = "" Or Trim(txtsubject.Text) = "" Or Trim(rtbbody.Text) = "") Then
            MsgBox("Bạn phải nhập đầy đủ thông tin của email, vui lòng thực hiện lại!", MsgBoxStyle.Exclamation, "Thông báo")
            test = 0
        Else
            test = 1
        End If
        Return test
    End Function

    Private Sub btnattach_Click(sender As System.Object, e As System.EventArgs) Handles btnattach.Click
        Dim SelectedFile As New System.Windows.Forms.OpenFileDialog
        Dim dlgResult As DialogResult = SelectedFile.ShowDialog()
        If dlgResult = Windows.Forms.DialogResult.OK Then
            txtattach.Text = SelectedFile.FileName
        End If
    End Sub

    Private Sub btnexit_Click(sender As System.Object, e As System.EventArgs) Handles btnexit.Click
        If MessageBox.Show("Bạn chắc chắn muốn thoát?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            Me.Close()
        End If
    End Sub

    
End Class